//
//  Member.swift
//  MKCodableTests
//
//  Created by 苏尚进 on 2020/5/9.
//  Copyright © 2020 moon. All rights reserved.
//

import Foundation
import MKCodable
import CoreLocation
import UIKit

extension CLLocationCoordinate2D : Codable {
    public static func initObject(from coder: Coder) throws -> CLLocationCoordinate2D {
        return try coder.decode(convertor: CLLocationCoordinate2DCodingConvertor())
    }
    public mutating func code(coder: Coder) throws {
        self .= (coder,CLLocationCoordinate2DCodingConvertor())
    }
}
public struct CLLocationCoordinate2DCodingConvertor : CodingConvertor {
    public typealias CodingType = CLLocationCoordinate2D
    public func decode(from coder: Coder) throws -> CLLocationCoordinate2D {
        let latitude:CLLocationDegrees = try coder["latitude"].decode()
        let longitude:CLLocationDegrees = try coder["longitude"].decode()
        let value = CLLocationCoordinate2D.init(latitude: latitude, longitude: longitude)
        return value;
    }
    
    public func encode(to coder: Coder, value: CLLocationCoordinate2D) throws {
        value.latitude => coder["latitude"]
        value.longitude => coder["longitude"]
    }
}

enum Gender:Int,Codable{
    case unkown = 0
    case male = 1
    case female = 2
}

class MemberBase : Codable{
    var name:String?
    var nickName:String?
    var gender:Gender = .unkown
    var age:Int?
    var phone:String?
    var photo:String?
    var birthday:Date?
    var location:CLLocationCoordinate2D?
    var income:Decimal?
    var favariteColor:UIColor?
    
    static func initObject(from coder: Coder) throws -> Self {
        let obj = self.init()
        try obj.code(coder: coder)
        return obj
    }
    public func code(coder: Coder) throws {
        self.location .= coder["location"]
        self.birthday .= (coder["birthday"],DateCodingConvertor(.dateFormatter("yyyy-MM-dd HH:mm:ss"), .chain([.secondsSince1970,.dateFormatter("yyyy-MM-dd HH:mm:ss")])))
        self.name .= coder["name"]
        self.nickName .= coder["nickName"]
        self.gender .= (coder["gender"],EnumCodingConvertor<String,Gender>(["m":.male,"f":.female]))
        self.age .= coder["age"]
        self.phone .= coder["phone"]
        self.photo .= coder["photo"]
        self.income .= coder["income"]
    }
    required init() {
    }
}
class Member : MemberBase{
    var money:NSNumber?
    public override func code(coder: Coder) throws {
        try super.code(coder: coder)
        self.money .= coder["money"]
    }
}

